package com.cmdb.web.controller.system;

import com.cmdb.common.core.domain.AjaxResult;
import com.cmdb.common.utils.StringUtils;
import com.cmdb.web.config.MiniosProperties;
import io.minio.*;
import io.minio.http.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 文件上传下载控制器
 */
@RestController
@RequestMapping("/system/file")
public class SysFileController {

    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MiniosProperties miniosProperties;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            String bucketName = miniosProperties.getBucketName();
            log.info("Starting file upload to bucket: {}", bucketName);

            // 检查存储桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                log.info("Bucket {} not found, creating new bucket", bucketName);
                // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") +
                            originalFilename.substring(originalFilename.lastIndexOf("."));

            log.info("Uploading file: {} to bucket: {}", fileName, bucketName);

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());

            log.info("File uploaded successfully: {}", fileName);

            // 获取文件访问URL
            String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .method(Method.GET)
                    .build());

            log.info("Generated URL: {}", url);

            Map<String, String> data = new HashMap<>();
            data.put("fileName", fileName);
            String yjurl = miniosProperties.getEndpoint() + "/"+miniosProperties.getBucketName()+"/"+fileName;
            data.put("url", yjurl);

            return AjaxResult.success(data);
        } catch (Exception e) {
            log.error("File upload failed", e);
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(fileUrl)) {
                throw new RuntimeException("文件地址不能为空");
            }

            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            fileName = fileName.contains("?") ? fileName.substring(0, fileName.indexOf("?")) : fileName;

            // 获取文件流
            InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                    .bucket(miniosProperties.getBucketName())
                    .object(fileName)
                    .build());

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                             URLEncoder.encode(fileName, "UTF-8"));

            // 写入响应流
            org.apache.commons.io.IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("fileName") String fileName) {
        try {
            if (StringUtils.isEmpty(fileName)) {
                return AjaxResult.error("文件名不能为空");
            }

            minioClient.removeObject(
                RemoveObjectArgs.builder()
                    .bucket(miniosProperties.getBucketName())
                    .object(fileName)
                    .build());

            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("文件删除失败：" + e.getMessage());
        }
    }
}